import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { Table, Input, Space, Button, message, Popconfirm } from 'antd';
import {
    UploadOutlined,
    DownloadOutlined,
    DeleteOutlined,
    InboxOutlined,
    CloseCircleOutlined,
} from '@ant-design/icons';

import { getSuggestWorksList, updateSuggestWorksStatus } from '@/api/manage';

const { Search } = Input;

export default function WorksManaComponent(props) {
    const { type } = props;
    const location = useLocation();
    const [articleList, setArticleList] = useState([]);
    const [searchValue, setSearchValue] = useState('');
    const [loading, setLoading] = useState(false);
    const [isRefresh, setIsRefresh] = useState(true);

    const handleShelf = async (id) => {
        console.log('上架文章 ID:', id);
        await updateSuggestWorksStatus(type, id, 'publish').then(() => {
            setIsRefresh(true);
            message.success('上架成功');
        });
    };

    const handleOffShelf = async (id) => {
        console.log('下架文章 ID:', id);
        await updateSuggestWorksStatus(type, id, 'unpublish').then(() => {
            setIsRefresh(true);
            message.success('下架成功');
        });
    };

    const handleDelete = async (id) => {
        console.log('删除文章 ID:', id);
        await updateSuggestWorksStatus(type, id, 'delete').then(() => {
            setIsRefresh(true);
            message.success('删除成功');
        });
    };

    const handleSearch = (value) => {
        console.log('搜索关键词:', value);
        setSearchValue(value);
        handleRequest(value);
    };

    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '地区',
            dataIndex: 'cityName',
            key: 'cityName',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => (
                <span
                    style={{
                        color: ['#52c41a', '#fa8c16', '#ff4d4f'][text],
                        fontWeight: 500,
                    }}
                >
                    {['已下架', '已上架', '已删除'][text]}
                </span>
            ),
        },
        {
            title: '发布时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space split={<span className="ant-divider" />}>
                    {record.status === 0 ? (
                        <Button type="link" icon={<UploadOutlined />} onClick={() => handleShelf(record.id)}>
                            上架
                        </Button>
                    ) : (
                        <Popconfirm
                            title="提示"
                            description="确认要下架该篇文章吗?"
                            okText="确认"
                            cancelText="取消"
                            onConfirm={() => handleOffShelf(record.id)}
                        >
                            <Button type="link" style={{ color: '#fa8c16' }} icon={<DownloadOutlined />}>
                                下架
                            </Button>
                        </Popconfirm>
                    )}
                    <Popconfirm
                        title="提示"
                        description="确认要删除该篇文章吗?"
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => handleDelete(record.id)}
                    >
                        <Button type="link" danger icon={<DeleteOutlined />}>
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];
    const handleRequest = async (searchText) => {
        if (searchText) {
            setLoading(true);
        }
        try {
            const res = await getSuggestWorksList(type, searchText);
            setArticleList(res.data);
        } finally {
            if (searchText) {
                setLoading(false);
            }
        }
    };

    useEffect(() => {
        if (isRefresh) {
            handleRequest();
            setIsRefresh(false);
        }
    }, [isRefresh]);

    return (
        <div
            style={{
                padding: '24px',
                background: '#fff',
                minHeight: 360,
                gap: 16,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'left',
            }}
        >
            <Search
                placeholder="请输入文章标题"
                enterButton="搜索"
                size="middle"
                style={{ width: 300 }}
                loading={loading}
                onSearch={handleSearch}
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                suffix={
                    <CloseCircleOutlined
                        onClick={() => {
                            setSearchValue('');
                            handleRequest('');
                        }}
                        style={{
                            color: searchValue ? 'rgba(0, 0, 0, 0.25)' : 'transparent',
                            cursor: 'pointer',
                            marginRight: 8,
                            transition: '0.3s',
                        }}
                    />
                }
            />
            <Table
                dataSource={articleList}
                columns={columns}
                style={{ width: '100%' }}
                locale={{
                    emptyText: (
                        <div
                            style={{
                                padding: '24px 0',
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                color: 'rgba(0, 0, 0, 0.25)',
                            }}
                        >
                            <InboxOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                            <span>暂无数据</span>
                        </div>
                    ),
                }}
            />
        </div>
    );
}
